﻿using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;

namespace XbmcManager.Modules
{
    public class XbmcLauncher
    {
        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
        private static extern bool ShowWindow(IntPtr hWnd, int cmdShow);

        private const int SW_SHOWMAXIMIZED = 3;

        /// <summary>
        /// Attempt to bring an existing XBMC to the foreground.
        /// If none exists, open XBMC.
        /// </summary>
        public void Start()
        {
            if (!BringProcessToForeground())
            { StartXBMC(); }
        }

        /// <summary>
        /// Determine if 32 or 64bit version is installed and start appropriate exe
        /// </summary>
        private void StartXBMC()
        {
            string xbmcPath = null;

            // Attempt to find the XBMC executable location via the registry
            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\XBMC");

            if (key != null) // If the path is in the registry use it to open XBMC
            {
                xbmcPath = key.GetValue("") as string;
                if (LaunchXBMCProcess(xbmcPath + @"\XBMC.exe"))
                    return;
            }
            else // Otherwise, we'll try to use the default locations
            {
                string x86Path = @"C:\Program Files\XBMC\XBMC.exe";
                string x64Path = @"C:\Program Files (x86)\XBMC\XBMC.exe";

                if (LaunchXBMCProcess(x86Path))
                    return;
                else
                    LaunchXBMCProcess(x64Path);
            }
        }

        /// <summary>
        /// Launch XBMC with user args
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private bool LaunchXBMCProcess(string path)
        {
            if (path != null && File.Exists(path))
            {
                string args = "";
                Process proc = new Process();

                if (File.Exists("XBMCLaunchArgs.txt"))
                {
                    using (StreamReader argStream = File.OpenText("XBMCLaunchArgs.txt"))
                    {
                        args = argStream.ReadLine();
                        argStream.Close();
                    }
                }

                proc.StartInfo = new ProcessStartInfo(path, args);
                proc.Start();
                BringProcessToForeground();
                return true;
            }
            return false;
        }

        /// <summary>
        /// If XBMC is currently running, bring it to the foreground
        /// </summary>
        /// <returns></returns>
        private bool BringProcessToForeground()
        {
            Process[] processes = Process.GetProcessesByName("XBMC");
            if (processes.Length != 0)
            {
                IntPtr hWnd = processes[0].MainWindowHandle;
                ShowWindow(hWnd, SW_SHOWMAXIMIZED);
                SetForegroundWindow(hWnd);
                return true;
            }
            return false;
        }
    }
}